package cn.CommonUtils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.util.NumberUtils;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

/**
 * Properties配置工具类
 */
@Slf4j
public class ApplicationPropertiesUtils implements PropertiesUtil {
    private Properties properties;

    /**
     * 指定配置文件
     */
    private static final String APPLICATIONCONFIGURATIONPROPERTIESFILENAME = "application.properties";

    public ApplicationPropertiesUtils() {
        InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream(APPLICATIONCONFIGURATIONPROPERTIESFILENAME);
        properties = new Properties();
        try {
            properties.load(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public ApplicationPropertiesUtils(String propertyPath) {
        InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream(propertyPath);
        properties = new Properties();
        try {
            properties.load(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    @Override
    public Properties getProperties() {
        InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream(APPLICATIONCONFIGURATIONPROPERTIESFILENAME);
         properties = new Properties();
        try {
            properties.load(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return properties;
    }

    /**
     * 读取配置项 - 字符串
     * @param key
     * @return
     */
    @Override
    public String getProperty(String key) {
        return this.properties.getProperty(key);
    }

    @Override
    public Object setProperty(String key, String value) {
        return this.properties.setProperty(key, value);
    }

    /**
     * 读取配置 - 长整形
     * @param key
     * @return
     */
    @Override
    public Long getPropertyByLong(String key) {
        String temp = this.properties.getProperty(key);

        for (int i = 0; i < temp.length()-1; i++) {
            if ( ! Character.isDigit(temp.charAt(i))) {
                log.error("getPropertyByLong 配置项的value出现非数字："+key);
                return null;
            }

        }

        return Long.parseLong(temp);
    }
}
